// 坐骑系统相关的WebSocket指令处理器
// 专门处理坐骑相关的功能

import { Injectable } from "@nestjs/common";
import { MountBaseService } from "../services/mount-base.service";
import { CharacterMountService } from "../services/character-mount.service";
import { MountLevelExperienceService } from "../services/mount-level-experience.service";

export type MountWsHandler = (
  payload: any,
  helpers: {
    userId: number;
    selectedCharacterId?: number;
    mountBaseService: MountBaseService;
    characterMountService: CharacterMountService;
    mountLevelExperienceService: MountLevelExperienceService;
  }
) => Promise<any> | any;

@Injectable()
export class MountWsHandlers {
  constructor(
    private readonly mountBaseService: MountBaseService,
    private readonly characterMountService: CharacterMountService,
    private readonly mountLevelExperienceService: MountLevelExperienceService
  ) {}

  /**
   * 处理获取坐骑列表指令
   * 指令格式: {c:4423}
   * 返回所有坐骑基础数据列表，并根据玩家坐骑表设置状态
   * s状态：0未购买 1未出战 2已出战
   */
  async handleGetMountList(payload: any, helpers: any): Promise<any> {
    try {
      console.log("处理4423指令：获取坐骑列表");

      const { selectedCharacterId } = helpers;

      if (!selectedCharacterId) {
        return {
          act_id: 4423,
          code: -1,
          msg: "未选择角色",
          data: [],
        };
      }

      // 获取所有坐骑基础数据
      const mountList = await this.mountBaseService.getAllMounts();

      // 获取玩家的坐骑数据
      const playerMounts = await this.characterMountService.getCharacterMounts(
        selectedCharacterId
      );

      // 创建坐骑ID到状态的映射
      const mountStatusMap = new Map<
        number,
        { status: number; characterMountId: number }
      >();
      playerMounts.forEach((mount) => {
        mountStatusMap.set(mount.mountBaseId, {
          status: mount.status, // 1未出战 2已出战
          characterMountId: mount.id,
        });
      });

      // 处理坐骑列表，设置正确的状态
      const processedMountList = mountList.map((mount) => {
        const playerMount = mountStatusMap.get(mount.id);

        if (playerMount) {
          // 玩家拥有此坐骑
          return {
            ...mount,
            id: playerMount.characterMountId, // 使用玩家坐骑ID
            s: playerMount.status, // 1未出战 2已出战
          };
        } else {
          // 玩家未购买此坐骑
          return {
            ...mount,
            id: 0, // 未购买时ID为0
            s: 0, // 0未购买
          };
        }
      });

      return {
        act_id: 4423,
        code: 0,
        data: processedMountList,
      };
    } catch (error: any) {
      console.error("获取坐骑列表失败:", error);
      return {
        act_id: 4423,
        code: -1,
        msg: error?.message || "获取坐骑列表失败",
        data: [],
      };
    }
  }

  /**
   * 处理获取坐骑详情指令
   * 指令格式: {c:4421,d:{id:坐骑ID}}
   * 根据坐骑ID返回详细信息
   */
  async handleGetMountDetail(payload: any, helpers: any): Promise<any> {
    try {
      const { id } = payload;

      if (!id) {
        return {
          act_id: 4421,
          code: -1,
          msg: "缺少坐骑ID参数",
        };
      }

      console.log(`处理4421指令：获取坐骑详情，ID: ${id}`);

      const mountDetail = await this.mountBaseService.getMountById(id);

      if (!mountDetail) {
        return {
          act_id: 4421,
          code: -1,
          msg: `坐骑ID ${id} 不存在`,
        };
      }

      return {
        act_id: 4421,
        code: 0,
        data: mountDetail,
      };
    } catch (error: any) {
      console.error("获取坐骑详情失败:", error);
      return {
        act_id: 4421,
        code: -1,
        msg: error?.message || "获取坐骑详情失败",
      };
    }
  }

  /**
   * 处理训练坐骑指令
   * 指令格式: {c:4420,d:{id:坐骑ID,t:"1"}}
   * 训练坐骑，每天每匹上限20次
   */
  async handleTrainMount(payload: any, helpers: any): Promise<any> {
    try {
      const { id, t } = payload;
      const { selectedCharacterId } = helpers;

      if (!id) {
        return {
          act_id: 4420,
          code: -1,
          msg: "缺少坐骑ID参数",
        };
      }

      if (!selectedCharacterId) {
        return {
          act_id: 4420,
          code: -1,
          msg: "请先选择角色",
        };
      }

      console.log(
        `处理4420指令：训练坐骑，角色ID: ${selectedCharacterId}, 坐骑ID: ${id}`
      );

      const result = await this.characterMountService.trainMount(
        selectedCharacterId,
        id
      );

      if (result.success) {
        return {
          act_id: 4420,
          code: 0,
          msg: result.message,
        };
      } else {
        return {
          act_id: 4420,
          code: -1,
          msg: result.message,
        };
      }
    } catch (error: any) {
      console.error("训练坐骑失败:", error);
      return {
        act_id: 4420,
        code: -1,
        msg: error?.message || "训练坐骑失败",
      };
    }
  }

  /**
   * 处理设置坐骑状态指令（出战/休息）
   * 指令格式: {c:4425,d:{id:坐骑ID,t:状态}}
   * t: 1-休息, 2-出战
   */
  async handleSetMountStatus(payload: any, helpers: any): Promise<any> {
    try {
      const { id, t } = payload;
      const { selectedCharacterId } = helpers;

      if (!id || t === undefined) {
        return {
          act_id: 4425,
          code: -1,
          msg: "缺少坐骑ID或状态参数",
        };
      }

      if (!selectedCharacterId) {
        return {
          act_id: 4425,
          code: -1,
          msg: "请先选择角色",
        };
      }

      console.log(
        `处理4425指令：设置坐骑状态，角色ID: ${selectedCharacterId}, 坐骑ID: ${id}, 状态: ${t}`
      );

      const result = await this.characterMountService.setMountStatus(
        selectedCharacterId,
        id,
        t
      );

      if (result.success) {
        return {
          act_id: 4425,
          code: 0,
        };
      } else {
        return {
          act_id: 4425,
          code: -1,
          msg: result.message,
        };
      }
    } catch (error: any) {
      console.error("设置坐骑状态失败:", error);
      return {
        act_id: 4425,
        code: -1,
        msg: error?.message || "设置坐骑状态失败",
      };
    }
  }

  /**
   * 处理获取当前出战坐骑信息指令
   * 指令格式: {c:4419}
   * 返回当前出战坐骑的详细信息
   */
  async handleGetActiveMountInfo(payload: any, helpers: any): Promise<any> {
    try {
      const { selectedCharacterId } = helpers;

      if (!selectedCharacterId) {
        return {
          act_id: 4419,
          code: -1,
          msg: "请先选择角色",
        };
      }

      console.log(
        `处理4419指令：获取出战坐骑信息，角色ID: ${selectedCharacterId}`
      );

      const result = await this.characterMountService.getActiveMountInfo(
        selectedCharacterId
      );

      if (result.success) {
        return {
          act_id: 4419,
          code: 0,
          data: result.data,
        };
      } else {
        return {
          act_id: 4419,
          code: -1,
          msg: result.message,
        };
      }
    } catch (error: any) {
      console.error("获取出战坐骑信息失败:", error);
      return {
        act_id: 4419,
        code: -1,
        msg: error?.message || "获取出战坐骑信息失败",
      };
    }
  }

  /**
   * 处理坐骑相关指令（购买/获取列表）
   * 指令格式:
   * - 购买坐骑: {c:4424,d:{id:坐骑基础ID}}
   * - 获取列表: {c:4424}
   */
  async handleMountOperation(payload: any, helpers: any): Promise<any> {
    try {
      const { selectedCharacterId } = helpers;

      if (!selectedCharacterId) {
        return {
          act_id: 4424,
          code: -1,
          msg: "请先选择角色",
        };
      }

      // 如果payload包含id，表示购买坐骑
      if (payload && payload.id) {
        console.log(
          `处理4424指令：购买坐骑，角色ID: ${selectedCharacterId}, 坐骑基础ID: ${payload.id}`
        );

        const result = await this.characterMountService.purchaseMount(
          selectedCharacterId,
          payload.id
        );

        if (result.success) {
          return {
            act_id: 4424,
            code: 0,
            msg: result.message || "坐骑购买成功",
          };
        } else {
          return {
            act_id: 4424,
            code: -1,
            msg: result.message || "坐骑购买失败",
          };
        }
      } else {
        // 否则获取角色坐骑列表
        console.log(
          `处理4424指令：获取角色坐骑列表，角色ID: ${selectedCharacterId}`
        );

        const mounts = await this.characterMountService.getCharacterMounts(
          selectedCharacterId
        );

        // 转换为前端需要的格式
        const mountList = mounts
          .map((mount) => {
            const base = (mount as any).mountBase || null;
            return {
              id: mount.id,
              name: base?.name || `坐骑#${mount.mountBaseId || mount.id}`,
              img: base?.img || "",
              level: mount.level,
              experience: mount.experience,
              transLevel: mount.transLevel,
              status: mount.status,
              currentAp: mount.currentAp,
              currentHp: mount.currentHp,
              currentMp: mount.currentMp,
              currentSp: mount.currentSp,
            };
          })
          .filter((m) => !!m);

        return {
          act_id: 4424,
          code: 0,
          data: mountList,
        };
      }
    } catch (error: any) {
      console.error("坐骑操作失败:", error);
      return {
        act_id: 4424,
        code: -1,
        msg: error?.message || "坐骑操作失败",
        data: [],
      };
    }
  }
}

// 导出处理器映射
export const mountWsHandlers: Record<number, MountWsHandler> = {
  // 4423: 获取坐骑基础列表指令
  4423: async (payload, helpers) => {
    const mountHandlers = new MountWsHandlers(
      helpers.mountBaseService,
      helpers.characterMountService,
      helpers.mountLevelExperienceService
    );
    return await mountHandlers.handleGetMountList(payload, helpers);
  },

  // 4421: 获取坐骑基础详情指令
  4421: async (payload, helpers) => {
    const mountHandlers = new MountWsHandlers(
      helpers.mountBaseService,
      helpers.characterMountService,
      helpers.mountLevelExperienceService
    );
    return await mountHandlers.handleGetMountDetail(payload, helpers);
  },

  // 4420: 训练坐骑指令
  4420: async (payload, helpers) => {
    const mountHandlers = new MountWsHandlers(
      helpers.mountBaseService,
      helpers.characterMountService,
      helpers.mountLevelExperienceService
    );
    return await mountHandlers.handleTrainMount(payload, helpers);
  },

  // 4425: 设置坐骑状态指令（出战/休息）
  4425: async (payload, helpers) => {
    const mountHandlers = new MountWsHandlers(
      helpers.mountBaseService,
      helpers.characterMountService,
      helpers.mountLevelExperienceService
    );
    return await mountHandlers.handleSetMountStatus(payload, helpers);
  },

  // 4419: 获取当前出战坐骑信息指令
  4419: async (payload, helpers) => {
    const mountHandlers = new MountWsHandlers(
      helpers.mountBaseService,
      helpers.characterMountService,
      helpers.mountLevelExperienceService
    );
    return await mountHandlers.handleGetActiveMountInfo(payload, helpers);
  },

  // 4424: 坐骑操作指令（购买/获取列表）
  4424: async (payload, helpers) => {
    const mountHandlers = new MountWsHandlers(
      helpers.mountBaseService,
      helpers.characterMountService,
      helpers.mountLevelExperienceService
    );
    return await mountHandlers.handleMountOperation(payload, helpers);
  },
};
